import React, { useRef,useState } from 'react';
import {
    Form,
    Select,
    DatePicker,
    Button,
    Space,
    Card,
    Tooltip
} from 'antd';
import {  PageContainer} from '@ant-design/pro-components';
import { SearchOutlined, RestOutlined } from '@ant-design/icons';
import {  useIntl } from '@umijs/max';
import type { ActionType,ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import dayjs from 'dayjs';
import { ApiLogRespVO } from '../types';
import { pagedApiLog } from '@/services/system/log_api';
import AddForm from './components/AddForm';
import { formatToLocalTime, toUTC } from "@/utils/time";


// const { RangePicker } = DatePicker;
// const { Option } = Select;


const ApiLogTable: React.FC = () => {
    const [form] = Form.useForm();
   const intl = useIntl();
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<ApiLogRespVO>();
    const actionRef = useRef<ActionType>();
    // 表格列定义
    const columns: ProColumns<ApiLogRespVO>[] = [
    {
      title: intl.formatMessage({ id: "pages.apiLog.orderCode" }),
      dataIndex: "orderCode",
      key: "orderCode",
      width: 120,
      render: (text) => text || "-",
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.referenceNo" }),
      dataIndex: "referenceNo",
      key: "referenceNo",
      width: 120,
      render: (text) => text || "-",
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.status" }),
      dataIndex: "statusCode",
      key: "statusCode",
      width: 60,
      render: (text) => text || "-",
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.requestUrl" }),
      dataIndex: "requestUrl",
      key: "requestUrl",
      width: 150,
      ellipsis: true,
      search: false,
      render: (text) => (
        <Tooltip title={text}>
          <span>{text || "-"}</span>
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.responseInfo" }),
      dataIndex: "responseBody",
      key: "responseBody",
      width: 150,
      render: (text) => (
        <Tooltip
          title={
            <div
              style={{
                maxWidth: "500px",
                maxHeight: "300px",
                overflow: "auto",
                wordBreak: "break-all",
                whiteSpace: "pre-wrap",
                color: "var(--tooltip-text-color)",
              }}
            >
              {text || "-"}
            </div>
          }
          overlayStyle={{ maxWidth: "500px" }}
        >
          <div
            style={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
              maxWidth: "100%",
            }}
          >
            {text || "-"}
          </div>
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.requestTime" }),
      dataIndex: "requestTime",
      key: "requestTime",
      width: 100,
      ellipsis: true,
      render: (_, record) => {
        return formatToLocalTime(record.requestTime);
      },
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.responseTime" }),
      dataIndex: "responseTime",
      key: "responseTime",
      width: 100,
      ellipsis: true,
      render: (_, record) => {
        return formatToLocalTime(record.responseTime);
      },
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.costTime" }),
      dataIndex: "costTime",
      key: "costTime",
      width: 80,
      render: (text) => text || "-",
    },
    {
      title: intl.formatMessage({ id: "pages.apiLog.actions" }),
      key: "action",
      width: 120,
      search: false,
      render: (_, record) => (
        <Space>
          <a onClick={() => showLogDetail(record)}>
            {intl.formatMessage({ id: "pages.apiLog.detail" })}
          </a>
        </Space>
      ),
    },
  ];

    // 显示日志详情
    const showLogDetail = (record: ApiLogRespVO) => {
        // console.log('日志详情:', record);
        // 这里可以打开一个模态框显示更多详情
         setCurrentRow(record);
        handleModalOpen(true);
    };

    // 重置查询表单
    const handleReset = () => {
        form.resetFields();
    };

    return (
      <PageContainer title={false}>
        <Card bordered={false}>
          <ProTable<ApiLogRespVO>
            headerTitle={intl.formatMessage({
              id: "pages.apiLog.title",
              defaultMessage: "API日志查询",
            })}
            rowKey="id"
            actionRef={actionRef}
            columns={columns}
            request={pagedApiLog}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
            }}
            form={{
              form,
              // 查询表单配置
              syncToUrl: true,
              syncToInitialValues: false,
            }}
            // toolBarRender={() => [
            //   <Button key="export" type="primary">
            //     导出日志
            //   </Button>,
            // ]}
            search={{
              // 自定义搜索表单
              optionRender: ({ searchText, resetText }, { form }) => [
                <Button
                  key="search"
                  type="primary"
                  onClick={() => {
                    form?.submit();
                  }}
                  icon={<SearchOutlined />}
                >
                  {searchText}
                </Button>,
                <Button
                  key="reset"
                  onClick={() => {
                    form?.resetFields();
                    form?.submit();
                  }}
                  icon={<RestOutlined />}
                >
                  {resetText}
                </Button>,
              ],
            }}
          />
        </Card>

        <AddForm
          // width="40%"
          visible={createModalOpen}
          values={currentRow}
          // onOpenChange={handleModalOpen}
          onCancel={async () => {
            handleModalOpen(false);
          }}
          onSuccess={function (): void {
            handleModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }}
        />
      </PageContainer>
    );
};

export default ApiLogTable;